package de.dopichaj.labrador.index.meta;


import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import de.dopichaj.labrador.index.IntervalSequence;
import de.dopichaj.labrador.index.TagFactory;
import de.dopichaj.labrador.index.IntervalSequence.Interval;
import de.dopichaj.labrador.search.hit.Hit;
import de.dopichaj.labrador.util.io.ByteReader;


/**
 * A mapping from Lucene IDs to XML document IDs.
 */
public final class HitFactory {
    
    private final Map<File, DocumentMetaData> digestMap =
        new HashMap<File, DocumentMetaData>();

    /**
     * Intervals and corresponding paths, used for mapping fragment IDs to
     * XML documents without disk access.
     */
    final IntervalSequence<File> limits = new IntervalSequence<File>();

    public HitFactory(final DocumentMetaDataFactory metaDataFactory,
        final ByteReader reader,
        final TagFactory tagFactory) throws IOException {
        
        try {
            load(metaDataFactory, reader, tagFactory);
        } catch (NumberFormatException e) {
            throw new IOException(
                "Illegal file format of fragment ID file:" + e);
        }
    }

    private void addLimit(int limit, File file, DocumentMetaData digest) {
        limits.add(limit - 1, file);
        digestMap.put(file, digest);
    }
    
    private void load(final DocumentMetaDataFactory metaDataFactory,
        final ByteReader reader, final TagFactory tagFactory)
        throws NumberFormatException, IOException {
        
        readDigests(metaDataFactory, tagFactory, reader,
            new DigestCollector() {

                public void collectDigest(DocumentMetaData digest) {
                    addLimit(digest.getEndId(), digest.getFile(), digest);
                }
            });
    }

    /**
     * An interface for collecting DocumentDigests.
     */
    public interface DigestCollector {
        public abstract void collectDigest(DocumentMetaData digest);
    }

    /**
     * Read DocumentDigests from an InputStream that contains a sequence of
     * digests written by {@link DocumentDigestOutputStream}. For each
     * digest read, the {@link DigestCollector#collectDigest(DocumentDigest)}
     * method is called.
     * @param tagFactory
     *          the tag factory to use for mapping tag IDs to tags.
     * @throws IOException
     */
    public static void readDigests(DocumentMetaDataFactory metaDataFactory,
        TagFactory tagFactory, ByteReader input,
        DigestCollector collector) throws IOException {

        try {
            while (true) {
                
                DocumentMetaData digest = metaDataFactory.makeMetaData(tagFactory, input);
                collector.collectDigest(digest);
            }
        } catch (EOFException e) {}
    }

    /**
     * Group the fragment IDs by the corresponding XML document.
     */
    public Map<File, Collection<Integer>>
        groupByDocument(List<Integer> fragmentIds) {

        return limits.groupByInterval(fragmentIds);
    }

    /**
     * Obtains Hits for the given IDs. The IDs must all come from the given
     * file.
     */
    public Map<Integer, Hit> getDocumentHits(File file, List<Integer> wantedIds) {
        
        final DocumentMetaData digest = digestMap.get(file);
        assert digest != null : "Digest for " + file + " is null";
        return digest.getFragments(wantedIds);
    }
    
    public Iterator<Interval<File>> limitIterator() {
        return limits.iterator();
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/